/*
 * @Date: 2022-02-24 16:23:12
 * @Autor: shenxin <3120200077@bit.edu.cn>
 */
#include <math.h>
#include <iostream>
using namespace std;


void interpFinderInter(
	const double table[], const int size, const double x, 
	int * lower, int * upper)
{
	int l = size;
	*lower = 0;
	*upper = 0;
	for (int i = 0; i < l; i++)
	{
		if (abs(x - table[i])<0.001)
		{
			*lower = i;
			*upper = i;
			break;
		}
		else if (x > table[i])
		{
			*lower = i;
			*upper = i + 1;
		}
		else
			break;
	}
}

// 两点插值函数
double interpCore(
	const double x1, const double x2, 
	const double y1, const double y2, const double x)
{
	if (abs(x1 - x2) < 0.001)
		return y1;
	else
		return ((y2 - y1) / (x2 - x1)*(x - x1) + y1);
}

// 一维插值
double interp1I1OInter(
	const double xtable[], const int size_x, 
    const double valuetable[], const double x)
{
	int lower, upper;
	interpFinderInter(xtable,size_x, x, &lower, &upper);
	return interpCore(xtable[lower], xtable[upper], valuetable[lower], valuetable[upper], x);
}

int main(){
    // double table[] = {1,2,3,4,5,6,7,8,9};
    double tablex[] = {1.1, 1.2, 1.3, 1.4, 1.8};
    double tabley[] = {2,   3,   4,    5,   6};
    int sizex = sizeof(tablex);
    int sizey = sizeof(tabley);
    double x = 1.5;
    int lower, upper;
    interpFinderInter(tablex, sizex , x, &lower, &upper);
    printf("lower = %d, upper = %d\n value[lower] = %f, value[upper] = %f\n", lower, upper, tablex[lower], tablex[upper]);
    double y = interp1I1OInter(tablex, sizex, tabley, x);
    printf("y = %f", y);
    return 0;
}
